package com.tros.admin.validation;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tros.customer.notification.MailNotification;

import java.util.Properties;

/**
 * Servlet implementation class AccReqValidation
 */
@WebServlet("/AccReqValidation")
public class AccReqValidation extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AccReqValidation() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub		

		 Connection connect =null;			 
		 HttpSession ses = request.getSession();
	
		 String fname = request.getParameter("name").trim();
	
		 
			try{
			       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			       connect =DriverManager.getConnection("jdbc:odbc:bank","root", " ");
		           System.out.println("DB Connection created :"+connect);
		           
		            if(request.getParameter("approve")!=null)
					 {				
		        	   System.out.println("---------------> came admin here 2--------->");
						 createUserCredentialsAccount(connect,fname,ses);	
				         response.sendRedirect("pendAccReq.jsp"); 
				         
					 }else{
						 System.out.println("---------------> came admin here 3--------->");
						 droptableinfodecline(connect,fname);	
				         response.sendRedirect("pendAccReq.jsp"); 
					 }
			}
			catch(Exception e)
			{ 
				System.out.println("+++++++++++ admin user"+e.getMessage());
		       	e.printStackTrace();
			}
			
	}
	
	private void createUserCredentialsAccount(Connection connect, String fname, HttpSession ses) {
		// TODO Auto-generated method stub
	
		String cust = createCustomerID();
		String pass = createPassword();

		saveCustidPass(connect,cust,pass,fname,ses);
	}


	private void saveCustidPass(Connection connect, String cust, String pass, String fname, HttpSession ses) {
		// TODO Auto-generated method stub
		
	    String LastName = null;
	    String Address=null;
	    String Dateofbirth=null;
	    String Gender=null;
	    String Email=null;
	    String Number=null;
		
		try
		{
			PreparedStatement state=connect.prepareStatement("SELECT * FROM NEWUSERS WHERE FIRSTNAME=?");
			state.setString(1,fname);
			ResultSet result=state.executeQuery();
			
			while(result.next()){
				
			     LastName=result.getString("LASTNAME");
			     Address=result.getString("ADDRESS");
			     Dateofbirth=result.getString("DATEOFBIRTH");
			     Gender=result.getString("GENDER");
			     Email=result.getString("EMAIL");
			     Number=result.getString("NUMBER");			    
			}
			state.close();
			
		}catch(Exception e){
			System.out.println("---------> error here cust id---->"+e.getMessage());
		}
		
		try{
			if(LastName != null)
			{
				updateExistUsers(connect,cust,pass,fname,LastName,Address,Dateofbirth,Gender,Email,Number,ses);				
			}		    
			
		}catch(Exception e){
			
			System.out.println("---------> error here drop id---->"+e.getMessage());
		}
		
	}

	
	private void updateExistUsers(Connection connect, String cust,String pass,
			String fname, String lastName, String address, String dateofbirth,
			String gender, String email, String number, HttpSession ses) {
		// TODO Auto-generated method stub
		
        try{			

		     System.out.println("Came here ==============>Address "+address);
		     
		    EncryptValue val = new  EncryptValue(pass); 
		    System.out.println("+++++++++ encrypt value ++++"+val.getEncryptValue());
		    
		    PreparedStatement state1=connect.prepareStatement("INSERT INTO EXISTUSERS VALUES(?,?,?,?,?,?,?,?,?)");
		    
		    state1.setString(1,cust);
		    state1.setString(2,val.getEncryptValue());
		    state1.setString(3,fname);
		    state1.setString(4,lastName);
		    state1.setString(5,address);
		    state1.setString(6,dateofbirth);
		    state1.setString(7,gender);
		    state1.setString(8,email);
		    state1.setString(9,number);
		   
		    
		    System.out.println("Came here ==============>Number "+number);
		    state1.executeUpdate();	
		    state1.close();
		    
		    MailNotification mail = new MailNotification(email);
		    
		    String text = "Welcome "+ lastName + 
		    		      "\n\n Please find your login credenials below for accessing Tros "+
		    		      "\n\n CustomerID : "+cust+
		    		      "\n Password : "+pass+
		    		      "\n\n Note : Please do not reply to this E-Mail Notification";
		    
		    mail.sendMail( "Login Credentials", text);
		    
		    System.out.println("Came here ==============>End ");	
			
		}catch(Exception e){
			System.out.println("update table--------->"+e.getMessage());
		}
        
        try{
        	
        	createSaveAcc(connect,cust,fname,lastName);
	        createCheckAcc(connect,cust,fname,lastName);
	        createMnyAcc(connect,cust);
			droptableinfo(connect,fname,cust,lastName);
			System.out.println("----------> mail start ");			 
			
        }catch(Exception E)
        {
        	System.out.println("Mail failed -------->"+E.getMessage());
        }
		
	}

	private void droptableinfo(Connection connect, String fname, String cust, String lname) {
		// TODO Auto-generated method stub
		
		try{
			
			PreparedStatement state=connect.prepareStatement("DELETE FROM NEWUSERS WHERE FIRSTNAME=?");
			state.setString(1,fname);
			state.executeUpdate();	
			state.close();
			
		}catch(Exception e){
			System.out.println("Drop table--------->"+e.getMessage());
		}
	}
	
	
	private void droptableinfodecline(Connection connect, String fname) {
		// TODO Auto-generated method stub
		
		try{
			
			PreparedStatement state=connect.prepareStatement("DELETE FROM NEWUSERS WHERE FIRSTNAME=?");
			state.setString(1,fname);
			state.executeUpdate();	
			state.close();
			
		}catch(Exception e){
			System.out.println("Drop table--------->"+e.getMessage());
		}
	}

	private void createCheckAcc(Connection connect, String cust, String fname, String lname) {
		// TODO Auto-generated method stub
		
		String chkAcc = createChkAcc();
		String intialVal = "0";		
		
       try{
			
    	    Calendar cal= Calendar.getInstance(); 
   	        cal.add(Calendar.YEAR, 10); 
   	    
   	        Date date = cal.getTime(); 
   	        
   	        SimpleDateFormat form = new SimpleDateFormat("MM/dd/yyyy");
   		    String day = form.format(date); 
   	        
    	    System.out.println("------------------> chk DATE ---------->"+day);
    	   
			PreparedStatement state=connect.prepareStatement("INSERT INTO CHCKACC VALUES(?,?,?,?,?,?)");
			state.setString(1,cust);
			state.setString(2,chkAcc);
			state.setString(3,intialVal);
			state.setString(4,day);
			state.setString(5,fname);
			state.setString(6,lname);
			state.executeUpdate();	
			state.close();
			
		}catch(Exception e){
			System.out.println("CHK table--------->"+e.getMessage());
		}
		
	}

	private void createSaveAcc(Connection connect, String cust, String fname, String lname) {
		// TODO Auto-generated method stub
		
		String savAcc = createSavAcc();
		String intialVal = "0";	
		
try{
			
    	    Calendar cal= Calendar.getInstance(); 
   	        cal.add(Calendar.YEAR, 10); 
   	    
   	        Date date = cal.getTime(); 
   	        
   	        SimpleDateFormat form = new SimpleDateFormat("MM/dd/yyyy");
		    String day = form.format(date); 
   	        
    	    System.out.println("------------------> sav DATE ---------->"+day);
    	   
			PreparedStatement state=connect.prepareStatement("INSERT INTO SAVACC VALUES(?,?,?,?,?,?)");
			state.setString(1,cust);
			state.setString(2,savAcc);
			state.setString(3,intialVal);
			state.setString(4,day);
			state.setString(5,fname);
			state.setString(6,lname);
			state.executeUpdate();	
			state.close();
			
		}catch(Exception e){
			System.out.println("SAV table--------->"+e.getMessage());
		}
	}

	
	private void createMnyAcc(Connection connect, String cust) {
		// TODO Auto-generated method stub
		
		String mnyCard = createMoneyCard();
		String intialVal = "0";	
		
try{
			    	   
			PreparedStatement state=connect.prepareStatement("INSERT INTO MNYCARD VALUES(?,?,?)");
			state.setString(1,cust);
			state.setString(2,mnyCard);
			state.setString(3,intialVal);
			state.executeUpdate();	
			state.close();
			
		}catch(Exception e){
			System.out.println("MNY table--------->"+e.getMessage());
		}
	}
	
	
	
	private String createChkAcc() {
		// TODO Auto-generated method stub
		
		Random random = new Random();			
		String chk = String.format("%010d", random.nextInt(1000000000));
		System.out.println("-----chk ---->"+chk);
		return chk;
	}

	private String createSavAcc() {
		// TODO Auto-generated method stub\
		
		Random random = new Random();			
		String sav = String.format("%010d", random.nextInt(1000000000));
		System.out.println("-----sav ---->"+sav);
		return sav;
	}
	
	private String createMoneyCard() {
		// TODO Auto-generated method stub\
		
		Random random = new Random();			
		String mny = String.format("%010d", random.nextInt(1000000000));
		System.out.println("-----sav ---->"+mny);
		return mny;
	}

	private String createPassword() {
		// TODO Auto-generated method stub
		
		char[] pattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
		Random random = new Random();

		StringBuilder builder = new StringBuilder((100000 + random.nextInt(900000)));
		for (int i = 0; i < 7; i++)
		{
			builder.append(pattern[random.nextInt(pattern.length)]);
		}
		String id = builder.toString();

		System.out.println("-----pass ---->"+id);
		return id;
	}

	private String createCustomerID() {
		// TODO Auto-generated method stub
		
		Random random = new Random();			
		String id = String.format("%08d", random.nextInt(100000000));
		System.out.println("-----cust ---->"+id);
		return id;
	}
	
	
}
